package sms_practice;

import java.sql.SQLException;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Consumer  extends Thread{
	static GoodsManagerImpl gmi = new GoodsManagerImpl();
	static Goods goods = new Goods();

	// 定义ActivMQ的连接地址
	private static final String ACTIVEMQ_URL = "tcp://127.0.0.1:61616";
	// 定义发送消息的队列名称
	private static final String QUEUE_NAME = "MessageFromSuperMarket";// MyMessage

	public void MessageReceive() throws JMSException {
		// 创建连接工厂
		ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
		// 创建连接
		Connection connection = activeMQConnectionFactory.createConnection();
		// 打开连接
		connection.start();
		// 创建会话
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		// 创建队列目标
		Destination destination = session.createQueue(QUEUE_NAME);
		// 创建消费者
		javax.jms.MessageConsumer consumer = session.createConsumer(destination);
		// 创建消费的监听
		consumer.setMessageListener(new MessageListener() {
			@Override
			public void onMessage(Message message) {
				TextMessage textMessage = (TextMessage) message;
				try {
					System.out.println("Consumer Receiving：" + textMessage.getText());
					String tempString = textMessage.getText();
//    	        	将记录添加到数据库
					String[] s = tempString.split("\\s+");

					goods.setName(s[0]);
					goods.setPrice(s[1]);
					goods.setUnit(s[2]);
					
					try {
						gmi.add(goods);
					} catch (SQLException e) {

						e.printStackTrace();
					}
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		});
		
		}
	@Override
	public void run() {
		try {
			this.MessageReceive();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	}